package com.bodacn.packapp.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.bodacn.packapp.DBUtil;
import com.bodacn.packapp.R;
import com.bodacn.packapp.SeachPauseBean;
import com.bodacn.packapp.adapter.SearchPauseAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

//查询暂存
public class SearchPauseActivity extends AppCompatActivity {

    @BindView(R.id.iv_on_package_back)
    ImageView ivOnPackageBack;
    @BindView(R.id.tv_on_package_back)
    TextView tvOnPackageBack;
    @BindView(R.id.tv_change)
    TextView tvChange;
    @BindView(R.id.tv_on_package_sure)
    TextView tvOnPackageSure;
    @BindView(R.id.lv)
    ListView lv;
    private String UserNo = "", BasketID = "", SeqNo = "";
    private final int MSG_GETLIST = 8001;
    private final int MSG_DELETE = 8002;
    //    private final int MSG_CHANGE = 8003;
    private final int MSG_Error = 8008;
    private JSONArray listJsonarray, deleteJsonarray;
    private List<SeachPauseBean> seachPauseBeanList = new ArrayList<>();
    private SearchPauseAdapter searchPauseAdapter;
    SeachPauseBean seachPauseBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_pause);
        ButterKnife.bind(this);
        UserNo = getIntent().getStringExtra("curLoginUserNo");
        searchPauseAdapter = new SearchPauseAdapter(this, seachPauseBeanList);
        lv.setAdapter(searchPauseAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (seachPauseBeanList.get(position).isCheck()) {
                    seachPauseBeanList.get(position).setCheck(false);
                    BasketID = "";
                    SeqNo = "";
                    seachPauseBean = null;
                } else {
                    for (int i = 0; i < seachPauseBeanList.size(); i++) {
                        seachPauseBeanList.get(i).setCheck(false);
                    }
                    seachPauseBeanList.get(position).setCheck(true);
                    BasketID = seachPauseBeanList.get(position).getBasketID();
                    SeqNo = seachPauseBeanList.get(position).getSeqNo();
                    seachPauseBean = seachPauseBeanList.get(position);

                }
                searchPauseAdapter.notifyDataSetChanged();
            }
        });
        search("SelectPauseBox", MSG_GETLIST);
    }

    @OnClick({R.id.tv_search, R.id.iv_on_package_back, R.id.tv_on_package_back, R.id.tv_change, R.id.tv_on_package_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_on_package_back:
            case R.id.tv_on_package_back:
                finish();
                break;
            case R.id.tv_search:
                search("SelectPauseBox", MSG_GETLIST);
                break;
            //切换
            case R.id.tv_change:
                if (TextUtils.isEmpty(BasketID)) {
                    Toast.makeText(SearchPauseActivity.this, "请选择需要切换的行", Toast.LENGTH_SHORT).show();
                    return;
                }
                EventBus.getDefault().post(new BackInfo(seachPauseBean.getBasketID(),seachPauseBean.getPoh(),seachPauseBean.getHh(),seachPauseBean.getHyh(),"pause"));
                finish();
//                change(MSG_CHANGE);
                break;
            //删除
            case R.id.tv_on_package_sure:
                if (TextUtils.isEmpty(BasketID)) {
                    Toast.makeText(SearchPauseActivity.this, "请选择需要删除的行", Toast.LENGTH_SHORT).show();
                    return;
                }
                search("DeletePauseBox", MSG_DELETE);
                break;
        }
    }

    private void search(String OperType, int msg) {
        String sqlFindcJname = "EXEC KeyPoint_Pack_MidGetSelectPauseBox @OperType='" + OperType + "',@UserNo='" + UserNo
                + "',@BasketID='" + BasketID + "',@SeqNo='" + SeqNo + "'";
        ReadSQLData(sqlFindcJname, msg);
    }

//    private void change(int msg) {
//        String sqlFindcJname = "Exec KeyPoint_Pack_MidScan @OperType='ScanBarcode',@Barcode='" + BasketID
//                + "',@BoxBarcode='',@ManuWorkGroup='"
//                + "',@OrderNo='',@StyleNo='"
//                + "',@PO='',@StyleSort='"
//                + "',@TaskID='',@Color='',@Size='"
//                + "',@UserNo='" + UserNo + "',@TermNo=''";
//        ReadSQLData(sqlFindcJname, msg);
//    }

    private void ReadSQLData(String sql, int type) {
        System.out.print("----存储过程:" + sql);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(sql);
                    System.out.print("----返回结果：" + jsonArray);
                    System.out.print("----过程：" + sql);
                    Message msg = new Message();
                    String OperType = "";
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType = jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE"))
                            OperType = jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.length() > 0) {
                            //获取列表
                            if (OperType.equals("SelectPauseBox")) {
                                listJsonarray = jsonArray;
                                msg.what = type;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            //删除
                            if (OperType.equals("DeletePauseBox")) {
                                deleteJsonarray = jsonArray;
                                msg.what = type;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            //切换
                            if (OperType.equals("ScanBarcode")) {
                                deleteJsonarray = jsonArray;
                                msg.what = type;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("HintInfo", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_Error;
                            errmsg.setData(bundle);
                            handler.removeMessages(errmsg.what);
                            handler.sendMessage(errmsg);
                        }
                    } else {
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("HintInfo", "未返回任何数据!");
                        errmsg.what = type;
                        errmsg.setData(bundle);
                        handler.removeMessages(errmsg.what);
                        handler.sendMessage(errmsg);
                    }

                } catch (Exception e) {
                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("HintInfo", "未返回任何数据!");
                    msg.what = MSG_Error;
                    msg.setData(bundle);
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle;
            switch (msg.what) {
                //获取列表
                case MSG_GETLIST:
                    System.out.println("MSG_GETLIST");
                    if (listJsonarray != null && listJsonarray.length() > 0) {
                        try {
                            if (listJsonarray.getJSONObject(0).has("ResultInfo")) {
                                Toast.makeText(SearchPauseActivity.this, listJsonarray.getJSONObject(0).getString("ResultInfo"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        List<SeachPauseBean> seachPauseBeans = new Gson().fromJson(String.valueOf(listJsonarray), new TypeToken<List<SeachPauseBean>>() {
                        }.getType());
                        seachPauseBeanList.clear();
                        seachPauseBeanList.addAll(seachPauseBeans);
                        searchPauseAdapter.notifyDataSetChanged();
                    } else {
                        seachPauseBeanList.clear();
                        searchPauseAdapter.notifyDataSetChanged();
                    }
                    break;
                //删除 切换
                case MSG_DELETE:
                    if (deleteJsonarray != null && deleteJsonarray.length() > 0) {
                        try {
                            if (deleteJsonarray.getJSONObject(0).has("ResultInfo")) {
                                BasketID = "";
                                SeqNo = "";
                                search("SelectPauseBox", MSG_GETLIST);
                                Toast.makeText(SearchPauseActivity.this, deleteJsonarray.getJSONObject(0).getString("ResultInfo"), Toast.LENGTH_SHORT).show();

                            }
                            if (deleteJsonarray.getJSONObject(0).has("ErrInfo")) {
                                AlertDialog alertDialog = new AlertDialog.Builder(SearchPauseActivity.this)
                                        .setTitle("系统提示").setMessage(deleteJsonarray.getJSONObject(0).getString("ResultInfo"))
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                return;
                                            }
                                        }).create(); // 创建对话框
                                alertDialog.show(); // 显示对话框
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(SearchPauseActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case MSG_Error:
                    bundle = msg.getData();
                    Toast.makeText(SearchPauseActivity.this, bundle.getString("HintInfo"), Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

}
